<?php

namespace app\common\model;


use think\Exception;

class MallOrderGoods extends Base
{
    protected $deleteTime = false;
    public function getByOrderGoodsList($id, $field = '*')
    {
        return $this->field($field)
            ->where("order_id", $id)
            ->select()
            ->toArray();
    }


    /**
     * @param $value
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getGetGoodsAttr($value)
    {
        if (empty($value)) {
            return '';
        }
        //查询id
        $goods = $this->where('order_id', $value)
            ->select()
            ->toArray();
        if (empty($goods)) {
            return "";
        }else{
            return array_column($goods,'goods_name');
        }
    }

    /**
     * @param int $order_id
     * @param null $with
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderGoodsByOrderIdAll(int $order_id = 0,$with = null): array
    {
        return $this
            ->field('*,option_id as get_specs_value')
            ->where('order_id',$order_id)
            ->with($with)
            ->select()
            ->toArray();
    }
    public function goods(){
        return $this->hasOne(MallGoods::class,'id','goods_id');
    }
    public function goodsSku(){
        return $this->hasOne(MallGoodsSku::class,'id','option_id');
    }
    /**
     * @param int $order_id
     * @return false|\think\Collection
     * @throws Exception
     */
    public function setOrderGoodsBySale(int $order_id = 0){
        try {
            $row = $this->where('id', $order_id)
                ->with('goodsSku')
                ->select()
                ->toArray();
        }catch (\Exception $e){
            throw new Exception("操作失败");
        }
        if(empty($row)){
            return false;
        }
        $update_data = [];
        foreach ($row as $v) {
            $update_data[] = [
                "id"=>$v['goodsSku']['id'],
                "sale_count" => $v['goodsSku']['sale_count'] + $v['total']
            ];
        }
        return (new MallGoodsSku())->saveAll($update_data);
    }


    /**
     * @param array $ids
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderGoodsByOrderIdsAll(array $ids = []): array
    {
        return $this->whereIn('order_id',$ids)
            ->with('goodsSku')
            ->select()
            ->toArray();
    }
}